import express from 'express'
import path from 'path'
import fs from 'fs'
import Translate from './translate.js'

const app = express()

app.use(express.static('language'))
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const __dirname = path.resolve(path.dirname(''));
const translate = new Translate({
    appid: '20210722000895276',
    key: 'fvlo2Rvw4h27gJQ4sheh',
})

app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, './', 'index.html'));
});

app.put('/updata/file', function(req, res){
    fs.writeFileSync('./language/'+req.body.path,req.body.content,'utf-8')
    res.send({
        code: 200,
    })
});

app.get('/getDir', function(req, res){
    let dirs = {};
    let dirFiles =  fs.readdirSync('./language')
    dirFiles.forEach(dir => {
        let files = fs.readdirSync('./language/'+dir)
        dirs[dir] = {}
        files.forEach(path => {
            dirs[dir][path] = fs.readFileSync('./language/'+dir+'/'+path, "utf8")
        })
    })
    res.send({
        code: 200,
        data: dirs
    })
});

app.get('/translate', function(req, res){
    translate.setOpt({
        startLang: req.query.startLang,
        endLang: req.query.endLang,
    })
    try {
        translate.startFN((err)=>{
            res.send(err||{
                code: 200,
            })
        })
    } catch (error) {
        res.send({
            code: 500,
        })
    }
});

app.listen(8888);